package OssProvider

import (
	"Volta/Config"
	"io"
	"mime/multipart"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"os"
)
type Oss struct {
	Conn *oss.Bucket
}

func (ossPr *Oss) Connect() error{
	var endpoint string = Config.Server.OssEndpoint
	var accessKeyId string = Config.Server.OssAccessKeyId
	var accessKeySecret string = Config.Server.OssAccessKeySecret
	var bucket string = Config.Server.OssBucket
	client, err := oss.New(endpoint,accessKeyId,accessKeySecret)
	if err != nil {
		return err
	}
	// 获取存储空间。
	bucketPr, err1 := client.Bucket(bucket)
	if err1 != nil {
		return err1
	}
	ossPr.Conn = bucketPr
	return nil
}

func (ossPr *Oss) GetOss() *oss.Bucket  {
	return ossPr.Conn
}

func (ossPr *Oss)SaveUploadedFile(file *multipart.FileHeader, dst string) error {
	src, err := file.Open()
	if err != nil {
		return err
	}
	defer src.Close()

	out, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer out.Close()

	_, err = io.Copy(out, src)
	return err
}

func (ossPr *Oss) HostUrl() string{
	return Config.Server.OssUrlhost
}